package com.cy.aircompressor.main.home.fragment.provider;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.cy.aircompressor.R;
import com.cy.aircompressor.databinding.ItemBannerCompressorLayoutBinding;
import com.cy.aircompressor.entity.compressor.Compressor;
import com.drug.lib.util.DensityUtil;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.youth.banner.adapter.BannerAdapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CompressorAdapter extends BannerAdapter<Compressor, CompressorAdapter.BannerViewHolder> {
    Context mContext;

    public CompressorAdapter(Context mContext, List<Compressor> mDatas) {
        //设置数据，也可以调用banner提供的方法,或者自己在adapter中实现
        super(mDatas);
        this.mContext = mContext;
    }


    //创建ViewHolder，可以用viewType这个字段来区分不同的ViewHolder
    @Override
    public BannerViewHolder onCreateHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        return new BannerViewHolder(ItemBannerCompressorLayoutBinding.inflate(inflater, parent, false));
    }

    @Override
    public void onBindView(BannerViewHolder holder, Compressor data, int position, int size) {
        float degree = getCompressorHealth(data.getNextMaintenanceDate());
        initPieChart(holder.mViewBinding.pieChart, degree);
        holder.mViewBinding.airName.setText(data.getName());
        holder.mViewBinding.runStatusImg.setImageDrawable(ContextCompat.getDrawable(mContext, data.getRunningState() == 0 ? R.mipmap.img_compressor_stop_status : R.mipmap.img_compressor_running_status));
        holder.mViewBinding.runStatusText.setText(data.getRunningStateDesc());
        holder.mViewBinding.runStatusText.setTextColor(Color.parseColor((data.getRunningState() == 0) ? "#BC3B3B" : "#59BC3B"));
    }

    /**
     * 获取健康度
     *
     * @param nextMaintenanceDate
     * @return
     */
    private float getCompressorHealth(String nextMaintenanceDate) {
        float point = 0;
        long nextMaintenanceTime = 0;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format.parse(nextMaintenanceDate);
            nextMaintenanceTime = date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long health = nextMaintenanceTime - System.currentTimeMillis();
        if (health < 0) {
            point = 30f;
        } else {
            int dayCount = (int) Math.ceil(health / (1000 * 60 * 60 * 24));
            if (dayCount >= 350) {
                point = 100f;
            } else {
                point = 100f - ((350 - dayCount) / 5);
            }
        }
        return point;
    }

    private String getPieChartColor(float degree) {
        if (degree <= 30f)
            return "#BC3B3B";
        else if (degree > 30f && degree < 70f)
            return "#BC623B";
        else
            return "#59BC3B";
    }

    private void initPieChart(PieChart pieChart, float degree) {
        // 设置是否使用百分比
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setDragDecelerationFrictionCoef(0.95f);

// 设置中间文字
        pieChart.setDrawCenterText(true);
        pieChart.setCenterText(generateCenterSpannableText(degree));
        pieChart.setCenterTextSize(6f);

// 设置空心圆
        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(Color.parseColor("#00000000"));
        // 设置圆孔半径
        pieChart.setHoleRadius(80f);
        // 设置空心圆的半径
        pieChart.setTransparentCircleRadius(100f);

        // 设置环形图和中间空心圆之间的圆环的颜色
        pieChart.setTransparentCircleColor(Color.parseColor("#FFFFFF"));
        // 设置环形图和中间空心圆之间的圆环的透明度
        pieChart.setTransparentCircleAlpha(0);

// 设置旋转角度
        pieChart.setRotationAngle(0);
        pieChart.setRotationEnabled(true);

// 设置图例
        Legend legend = pieChart.getLegend();
        legend.setForm(Legend.LegendForm.EMPTY);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.CENTER);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        legend.setDrawInside(false);
        legend.setEnabled(false);

// 设置条目标签
        pieChart.setEntryLabelColor(Color.BLUE);
        pieChart.setEntryLabelTextSize(18f);
        pieChart.setDrawEntryLabels(false);
        // 设置动画
        pieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // 描述信息
//        Description description = new Description();
//        description.setText("健康度");
//        description.setTextSize(6f);
//        description.setTextAlign(Paint.Align.CENTER);
//        description.setTextColor(Color.parseColor("#B4C0CC"));
//        pieChart.setDescription(description);

        setPieChartDatas(pieChart, degree);
    }

    private SpannableString generateCenterSpannableText(float degree) {

        String de = String.valueOf(degree);
        SpannableString s = new SpannableString(de + "  %\n健康度");
        s.setSpan(new AbsoluteSizeSpan(DensityUtil.sp2px(9f), false), 0, de.length(), 0);
        s.setSpan(new ForegroundColorSpan(Color.WHITE), 0, de.length(), 0);

        s.setSpan(new StyleSpan(Typeface.NORMAL), de.length(), s.length() - 3, 0);
        s.setSpan(new ForegroundColorSpan(Color.parseColor("#ABDFFF")), de.length(), s.length() - 3, 0);
        s.setSpan(new AbsoluteSizeSpan(DensityUtil.sp2px(4f), false), de.length(), s.length() - 3, 0);

        s.setSpan(new StyleSpan(Typeface.NORMAL), s.length() - de.length(), s.length(), 0);
        s.setSpan(new ForegroundColorSpan(Color.parseColor("#ABDFFF")), s.length() - de.length(), s.length(), 0);
        s.setSpan(new AbsoluteSizeSpan(DensityUtil.sp2px(4f), false), s.length() - de.length(), s.length(), 0);
        return s;
    }

    private void setPieChartDatas(PieChart pieChart, float degree) {
        List<PieEntry> yVals = new ArrayList<>();
        yVals.add(new PieEntry(100 - degree, ""));
        yVals.add(new PieEntry(degree, ""));

        List<Integer> colors = new ArrayList<>();
        colors.add(Color.WHITE);
        colors.add(Color.parseColor(getPieChartColor(degree)));

        PieDataSet pieDataSet = new PieDataSet(yVals, "");

        pieDataSet.setSliceSpace(3f);
        pieDataSet.setSelectionShift(5f);

        pieDataSet.setColors(colors);
        pieDataSet.setValueTextSize(0f);
        PieData pieData = new PieData(pieDataSet);
        pieChart.setData(pieData);
    }

    class BannerViewHolder extends RecyclerView.ViewHolder {
        ItemBannerCompressorLayoutBinding mViewBinding;

        public BannerViewHolder(@NonNull ViewBinding viewBinding) {
            super(viewBinding.getRoot());
            mViewBinding = (ItemBannerCompressorLayoutBinding) viewBinding;
        }
    }
}
